package com.ihealthway.all.testuitl;

import com.ihealthway.all.utils.Utils;
import com.ihealthway.all.groupbuy.vo.Reward;
import io.github.elkan1788.mpsdk4j.api.WechatAPI;
import io.github.elkan1788.mpsdk4j.api.WechatAPIImpl;
import io.github.elkan1788.mpsdk4j.common.EventType;
import io.github.elkan1788.mpsdk4j.vo.MPAccount;
import io.github.elkan1788.mpsdk4j.vo.api.Follower;
import io.github.elkan1788.mpsdk4j.vo.api.Follower2;
import io.github.elkan1788.mpsdk4j.vo.api.Menu;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Xmls;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.testng.annotations.Test;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A template tool for generate some info
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
public class TempGenerator {

    private static final Log logger = Logs.get();

    @Test
    public void testGenerateMD5Pswd() {
        SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");

        String expPswd = "20170718admin123";
        String md5Encry = Lang.md5(expPswd);
        logger.infof("MD5 Password: %s, length: %d", md5Encry, md5Encry.length());

        String devAK = Lang.md5("TlHqnxujE7dLopIKezRZ9rg1PDGm2Y08"+DATE_FORMAT.format(new Date()));
        String testAK = Lang.md5("vaKd5WAwIZueL01HQrPixJByNjqzCF2l"+DATE_FORMAT.format(new Date()));
        String prodAK = Lang.md5("SpcVQdoKba6v2Nnj1mtZM7DExCqf4TWw"+DATE_FORMAT.format(new Date()));
        logger.infof("dev: %s", devAK);
        logger.infof("test: %s", testAK);
        logger.infof("prod: %s", prodAK);
        logger.info(new Date(1494660623000L));
    }

//    @Test
    public void testCreateDevAccessToken() {
        MPAccount mpAct = new MPAccount();
        mpAct.setMpId("gh_dcc1e9f05cf1");
        mpAct.setAppId("wxf602a2bc7f5d189c");
        mpAct.setAppSecret("68c51bd8d22a28a0d0759dfbd631f13f");

        WechatAPI wechatAPI = WechatAPIImpl.create(mpAct);
        logger.infof("Develop access token: %s", wechatAPI.getAccessToken());

        List<Follower> followerList = wechatAPI.getFollowers(Lang.list(new Follower2("oa_djt3VhApMZ3EFXf9B0jGIqznQ", "zh_CN")));
        logger.infof("%s", followerList.get(0).toString());
        logger.infof("%s", new Date(followerList.get(0).getSubscribeTime()*1000L));

        Follower follower = wechatAPI.getFollower("oa_djt3VhApMZ3EFXf9B0jGIqznQ", "zh_CN");
        logger.infof("%s", follower);
    }

    @Test
    public void testCreateDevMenu() {
        Menu site = new Menu("微网站", EventType.VIEW.name(), "http://elkan1788.ngrok.wendal.cn/index.html");

        Menu shop = new Menu("团购", EventType.VIEW.name(), "http://elkan1788.ngrok.wendal.cn/front/shop/home.do");

        Menu personal = new Menu("会员信息", EventType.VIEW.name(), "http://elkan1788.ngrok.wendal.cn/front/personal/home.do");

        MPAccount mpAct = new MPAccount();
        mpAct.setMpId("gh_dcc1e9f05cf1");
        mpAct.setAppId("wxf602a2bc7f5d189c");
        mpAct.setAppSecret("68c51bd8d22a28a0d0759dfbd631f13f");

        logger.infof("{\"button\": %s}", Json.toJson(new Menu[] {site, shop, personal}));
        WechatAPI wechatAPI = WechatAPIImpl.create(mpAct);
        boolean flag = wechatAPI.createMenu(site, shop, personal);
        logger.infof("WeChat[%s] create custom menu success[%s].", mpAct.getMpId(), flag);
    }

//    @Test
    public void testCreateTestMenu() {
        Menu site = new Menu("微网站", EventType.VIEW.name(), "http://all.ihealthway.com/test/index.html");

        Menu shop = new Menu("团购", EventType.VIEW.name(), "http://all.ihealthway.com/test/front/shop/home.do");

        Menu personal = new Menu("会员信息");
        Menu orderList = new Menu("个人订单", EventType.VIEW.name(), "http://all.ihealthway.com/test/front/personal/home.do");
        Menu userInfo = new Menu("个人信息", EventType.CLICK.name(), "personal-info");
        personal.setSubButtons(Arrays.asList(orderList, userInfo));

        MPAccount mpAct = new MPAccount();
        /*mpAct.setMpId("gh_0ed312454fa0");
        mpAct.setAppId("wx67b71984dc4aba00");
        mpAct.setAppSecret("9203781f8b8692bec5810585461f8e1e");*/
        mpAct.setMpId("gh_20e50b3b4b1d");
        mpAct.setAppId("wxa822bd8795de1633");
        mpAct.setAppSecret("613d3cefcc98f71a875d1342c8325f3d");

        logger.infof("Menu: %s", Json.toJson(new Menu[] {site, shop, personal}));
        WechatAPI wechatAPI = WechatAPIImpl.create(mpAct);
        boolean flag = wechatAPI.createMenu(site, shop, personal);
        logger.infof("WeChat[%s] create custom menu success[%s].", mpAct.getMpId(), flag);
    }

//    @Test
    public void testCreateProdMenu() {

        Menu service = new Menu("健康服务");
        Menu house = new Menu("健康小屋", EventType.VIEW.name(), "https://www.ihealthway.com/pc/service/house.aspx");
        Menu pensoin = new Menu("居家养老", EventType.VIEW.name(), "https://www.ihealthway.com/pc/service/pension.aspx");
        Menu office = new Menu("职场医疗", EventType.VIEW.name(), "https://www.ihealthway.com/pc/service/office.aspx");
        Menu customize = new Menu("专属定制", EventType.VIEW.name(), "https://www.ihealthway.com/pc/service/customize.aspx");
        Menu site = new Menu("健维平台", EventType.VIEW.name(), "http://all.ihealthway.com/index.html");
        service.setSubButtons(Arrays.asList(house, pensoin, office, customize, site));


        Menu shop = new Menu("健康商城", EventType.VIEW.name(), "http://all.ihealthway.com/front/shop/home.do");

        Menu connect = new Menu("在线互动");
        Menu green = new Menu("在线预约", EventType.VIEW.name(), "https://www.ihealthway.com/pc/green/index.aspx");
        Menu contact = new Menu("联系我们", EventType.VIEW.name(), "https://www.ihealthway.com/pc/contact/index.aspx");
        connect.setSubButtons(Arrays.asList(green, contact));

        MPAccount mpAct = new MPAccount();
        mpAct.setMpId("gh_71469b0885f9");
        mpAct.setAppId("wx3793820ea81974ea");
        mpAct.setAppSecret("c281c93f4bb4ccf01370ae38d09326f2");

        logger.infof("{button: %s}", Json.toJson(new Menu[] {service, shop, connect}));
        WechatAPI wechatAPI = WechatAPIImpl.create(mpAct);
        boolean flag = wechatAPI.createMenu(service, shop, connect);
        logger.infof("WeChat[%s] create custom menu success[%s].", mpAct.getMpId(), flag);
    }

    @Test
    public void testDownloadFile() throws Exception {
        List<String> allowTypes = Arrays.asList("jpg", "jpeg", "bmp", "png", "git");
        String fileName = "test.png";
        long count = allowTypes.stream().filter(type -> fileName.toLowerCase().endsWith(type)).count();
        logger.infof("type: %d", count);
    }

    @Test
    public void testXmls() throws Exception {
        Map<String, Object> body = new HashMap<>();
        body.put("app_id", "wx_3290dxoladqwsdJfh");
        body.put("Sec", "1234565e");
        logger.infof("%s", Xmls.mapToXml(body));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String orderNo = sdf.format(new Date())+ Utils.buildRandom(4);
        logger.infof("orderNo: %s, length: %d", orderNo, orderNo.length());
    }

    @Test
    public void testUserAgent() throws Exception {
//        String userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_4 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/11B554a MicroMessenger/6.2.4 NetType/WIFI Language/zh_CN";
        String userAgent = "Mozilla/5.0 (Linux; U; Android 4.2.2; zh-cn; 2014011 Build/HM2014011) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 MicroMessenger/6.0.0.50_r844973.501 NetType/WIFI";
        String verRegex = "MicroMessenger\\/([\\d\\.]+)";
        String iphoneRegex = "iPhone\\s+OS\\s+([\\d\\_]+)";
        String androidRegex = "Android\\s+([\\d\\.]+)";
        String netRegex = "NetType\\/[0-9a-zA-Z]*";


        Pattern pattern = Pattern.compile("iPhone\\s+OS\\s+([\\d\\_]+)|Android\\s+([\\d\\.]+)|MicroMessenger\\/([\\d\\.]+)|NetType\\/[0-9a-zA-Z+]*", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(userAgent);
//        matcher.find();
//        logger.infof("%s", matcher.group(0));
        int i=0;
        while (matcher.find()) {
            switch (i) {
                case 0:
                    String os = matcher.group();
                    logger.infof("OS: %s", os.split(" ")[0]);
                    break;
                case 1:
                    String ver = matcher.group();
                    logger.infof("Version: %s", ver.split("/")[1]);
                    break;
                case 2:
                    String net = matcher.group();
                    logger.infof("Net: %s", net.split("/")[1]);
                    break;
            }
            i++;
        }
    }

    @Test
    public void testLuckDraw() throws Exception {
        List<Reward> rewards = new ArrayList<>();
        for (int i=0; i<2; i++) {
            Reward reward = new Reward();
            reward.setRewardId(i);
            reward.setRewardCount(10);
//            reward.setProbability(new BigDecimal("0.00001"));
            rewards.add(reward);
        }

        for (int i=0; i<2; i++) {

            int rewardId = Utils.luckDraw(rewards);
            Reward tmp = rewards.get(rewardId);
            tmp.setRewardCount(tmp.getRewardCount()-1);
//            if (tmp.getRewardCount()<=0){
//                rewards.remove(tmp);
//            } else {

                rewards.set(rewardId, tmp);
//            }
//            logger.infof("Lottery times:%d, win: %d", i, rewardId);
        }

        rewards.forEach(tmp -> {
            logger.infof("Lottery times:%d, count: %d", tmp.getRewardId(), tmp.getRewardCount());
        });

        String tmp = "123%1$sLee%2$sSen%1$s";
        logger.info(String.format(tmp, "456","789"));
    }
}
